package com.filldream.fastboot.common.okutil.cls;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.filldream.fastboot.common.okutil.cls.dto.*;
import com.filldream.fastboot.common.okutil.stock.cf.comment.dto.CfComment;
import com.filldream.fastboot.common.okutil.stock.cf.comment.dto.CfCommentPostUser;
import com.filldream.fastboot.common.util.TransferUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;

/**
 * 财联社工具类
 */
@Slf4j
public class ClsUtil {

    /**
     * 获取财联社头条新闻
     * @return
     */
    public static ClsNews getClsNews() {
        log.info("=========获取财联社头条新闻=========");
        String webResult = HttpUtil.get("https://www.cls.cn/v3/depth/home/assembled/1000?app=CailianpressWeb&os=web"
                + "&sv=7.7.5&sign=bf0f367462d8cd70917ba5eab3853bce"
        );
        log.info("获取财联社头条新闻:" + webResult.substring(0, 35));
        ClsBaseDTO<ClsNews> result = toResult(webResult, ClsNews.class);
        if( result.getErrno().equals(0) ){
            return result.getData();
        }
        log.error("获取财联社头条新闻失败:" + webResult);
        return null;
    }

    public static List<ClsNewsSimpleItem> getClsNewsList() {
        List<ClsNewsSimpleItem> result = new ArrayList<>();
        ClsNews clsNews = getClsNews();
        if( clsNews != null ) {
            if(ObjectUtils.isNotEmpty(clsNews.getTopArticle())){
                List<TopArticle> topArticle = clsNews.getTopArticle();
                for (TopArticle article : topArticle) {
                    ClsNewsSimpleItem o = TransferUtil.changeToObj(article, ClsNewsSimpleItem.class);
                    o.setId( article.getId() + "" );
                    o.setIsTop(true);
                    o.setSourceType(1);
                    o.setMediaName( article.getAuthor() );
                    o.setPublishTime( article.toCreateTime() );
                    result.add(o);
                }
            }
            List<DepthList> depthList = clsNews.getDepthList();
            if(ObjectUtils.isNotEmpty(depthList)){
                for (DepthList depth : depthList) {
                    ClsNewsSimpleItem o2 = TransferUtil.changeToObj(depth, ClsNewsSimpleItem.class);
                    o2.setId( depth.getId() + "" );
                    o2.setIsTop(false);
                    o2.setSourceType(1);
                    o2.setMediaName( depth.getSource() );
                    o2.setPublishTime( depth.toCreateTime() );
                    result.add(o2);
                }
            }
        }
        return result;
    }

    public static <T> ClsBaseDTO<T> toResult(String json, Class<T> clazz) {
        ClsBaseDTO<T> result = JSON.parseObject(json, new TypeReference<ClsBaseDTO<T>>(clazz) {
        });
        return result;
    }

    /**
     * 获取财联社的板块变动
     */
    public static List<ClsAnchorDTO> getClsAnchor(String date){
        List<ClsAnchorDTO> resultList = new ArrayList<>();
        String resultJson = HttpUtil.get("https://www.cls.cn/v3/transaction/anchor?app=CailianpressWeb&cdate=" + date + "&os=web&sv=8.4.6");
        JSONObject jsonObj = JSONObject.parseObject(resultJson);
        if( jsonObj.containsKey("errno") && jsonObj.getInteger("errno").equals(0) ){
            JSONArray data = jsonObj.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                ClsAnchorDTO item = new ClsAnchorDTO();
                item.setCTime( jsonObject.getString("c_time") );
                item.setIsUp( jsonObject.getString("float").equals("up") );
                item.setSymbolName( jsonObject.getString("symbol_name") );
                item.setSymbolCode( jsonObject.getString("symbol_code") );
                item.setArticleId( jsonObject.getLong("article_id") );
                resultList.add(item);
            }
        }
        return resultList;
    }

    /**
     * 获取财联社电报
     * @return  电报内容
     */
    public static List<String> getTelegraphList(){
        List<String> result = new ArrayList<>();
        String html = HttpUtil.get("https://www.cls.cn/telegraph");
        Document doc = Jsoup.parse(html);
        Elements divList = doc.getElementsByClass("clearfix m-b-15 f-s-16 telegraph-content-box");
        for (Element item : divList) {
            Elements spans = item.getElementsByTag("span");
            StringBuilder value = new StringBuilder();
            for (Element span : spans) {
                value.append(span.text());
            }
            result.add(value.toString());
        }
        return result;
    }

    public static List<CfComment> getTel(){
        List<CfComment> result = new ArrayList<>();
        String html = HttpUtil.get("https://www.cls.cn/telegraph");
        Element dataElement = Jsoup.parse(html).getElementById("__NEXT_DATA__");
        String json = dataElement.childNode(0).toString();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray telegraphList = jsonObject.getJSONObject("props").getJSONObject("initialState").getJSONObject("telegraph").getJSONArray("telegraphList");
        for (int i = 0; i < telegraphList.size(); i++) {
            JSONObject itemJson = telegraphList.getJSONObject(i);
            CfComment cfComment = new CfComment();
            cfComment.setChannelType(3);
            cfComment.setPost_id( itemJson.getLong("id") );
            cfComment.setStockName( StringUtils.isNotBlank(itemJson.getString("title")) ? itemJson.getString("title") : "财联社" );
            cfComment.setPost_content( itemJson.getString("content") );
            cfComment.setPost_publish_time( DateUtil.date(itemJson.getLong("ctime")*1000).toString("yyyy-MM-dd HH:mm:ss") );
            cfComment.setReply_list( new ArrayList<>() );
            cfComment.setPost_pic_url(new ArrayList<>());
            cfComment.setTheme("");
            cfComment.setPost_title("");
            CfCommentPostUser cfCommentPostUser = new CfCommentPostUser();
            cfCommentPostUser.setUser_age(cfComment.getChannelName());
            cfCommentPostUser.setUser_nickname( itemJson.containsKey("author") && StringUtils.isNotBlank(itemJson.getString("author")) ? itemJson.getString("author") : "财联社电报" );
            cfComment.setPost_user(cfCommentPostUser);
            //重置内容
            cfComment.setPost_content( cfComment.getPost_content().replaceFirst("【"+cfComment.getStockName()+"】","") );
            result.add(cfComment);
        }
        return result;
    }

}
